#include"sl.h"
sl* slbuynode(datatype x)
{
	sl* newnode = (sl*)malloc(sizeof(sl*));
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void pushback(sl** pphead, datatype x)
{
	assert(pphead);
	sl*newnode=slbuynode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
		return;
	}
	sl* ptail = *pphead;
	while (ptail->next)
	{
		ptail = ptail->next;
	}
	ptail->next = newnode;
}
void print(sl** pphead)
{
	sl* node = *pphead;
	while (node)
	{
		printf("%d -> ",node->data);
		node = node->next;
	}
	printf("NULL\n");
}
void pushfront(sl** pphead, datatype x)
{
	assert(pphead);
	sl* newnode = slbuynode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
		return;
	}
	newnode->next = *pphead;
	*pphead = newnode;
}
void popback(sl** pphead)
{
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next == NULL)
	{
		//free(*pphead);
		*pphead = NULL;
		return;
	}
	sl* pcur = *pphead;
	sl* ptail = NULL;
	while (pcur->next->next)
	{
		pcur = pcur->next;
	}
    ptail = pcur->next;
	pcur->next = NULL;
	//free(ptail);
}
void popfront(sl** pphead)
{
	assert(pphead);
	assert(*pphead);
	sl* pcur = *pphead;
	*pphead = pcur->next;
	//free(pcur);
}
sl* slfind(sl** pphead,datatype x)
{
	sl* pcur = *pphead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void insertfront(sl** pphead, sl* pos, datatype x)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);

	if (pos==*pphead)
	{
		pushfront(pphead,x);
		return;
	}
	sl* pcur = *pphead;
	sl* newnode = slbuynode(x);
	while (pcur->next!=pos)
	{
		pcur = pcur->next;
	}
	newnode->next = pos;
	pcur->next = newnode;
}
void insertback(sl* pos, datatype x)
{
	assert(pos);
	sl* newnode = slbuynode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void eraseback(sl* pos)
{
	assert(pos);
	/*sl* node = pos->next;
	free(node);*/
	pos->next = pos->next->next;

}
void destory(sl** pphead)
{
	sl* ph = NULL;
	sl* pcur = *pphead;
	while (pcur)
	{
		ph = pcur;
		pcur = pcur->next;
		free(ph);
	}
	*pphead = NULL;
}
